﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Core.Mgr.ABTest
{
    /// AB测试分组工具
    public static class AbRandomTool
    {
        /// 随机分组
        public static TestGroupInfo RandomGroup(List<TestGroupInfo> allTestGroup)
        {
            if (allTestGroup == null || allTestGroup.Count == 0)
            {
                Debug.LogError("AbRandomTool: allTestGroup == null 或 allTestGroup.Count = 0");
                return null;
            }

            if (!allTestGroup.Sum(item => item.Ratio).Equals(1))
            {
                Debug.LogError("AbRandomTool: 所有测试组比例的和不为1");
                return null;
            }

            int random = Util.Random(0, 1000000);
            int minLimit = 0;
            foreach (var testGroup in allTestGroup)
            {
                var maxLimit = (int) (testGroup.Ratio * 1000000) + minLimit;
                if (random < maxLimit && random >= minLimit)
                {
                    // 随机分组完成
                    return testGroup;
                }

                minLimit = maxLimit;
            }

            return allTestGroup[^1];
        }
    }

    [Serializable]
    public class TestGroupInfo
    {
        /// 该测试组的Id
        public string TestId = "A";

        /// 该测试组的比例,支持两位小数
        public float Ratio = 0;
    }
}